<template>
  <el-row>
    <el-col :span="8">
      <div class="action-wrap">
        <el-form inline>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="() => router.go(-1)">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="tableList" row-key="id" default-expand-all style="width: 100%">
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column prop="parent" label="父分类" align="center">
          <template #default="scope">
            <span>{{ getDocName(scope.row.parent) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="顺序" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="warning" link @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="16">
      <div style="padding: 0 0 20px 120px">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleRest">重置</el-button>
      </div>
      <el-form :model="form" label-width="120">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" :maxlength="18" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="父分类" prop="parent">
          <el-tree-select
            v-model="form.parent"
            :data="treeList"
            :render-after-expand="false"
            :props="{ label: 'name', value: 'id' }"
          />
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePreview">预览</el-button>
        </el-form-item>
        <el-form-item label="内容" prop="valueHtml">
          <Wangeditor v-model="valueHtml" />
        </el-form-item>
      </el-form>
    </el-col>
    <Drawer :visible="visible" title="预览" :showFooter="false" @cancel="() => (visible = false)">
      <div v-html="valueHtml"></div>
    </Drawer>
  </el-row>
</template>

<script setup>
import Wangeditor from '@/components/wangeditor/Wangeditor.vue'
import { getDocAll, saveDoc, deleteDoc, getContent } from '../../api/doc'
import { array2Tree, copy, isNotEmpty } from '@/utils/index.js'
import { useRoute, useRouter } from 'vue-router'
import Drawer from '@/components/drawer/Drawer.vue'

const router = useRouter()
const route = useRoute()

const sourceTreeList = ref([])
const tableList = ref([])
const treeList = ref([])
const docList = ref([])
const form = ref({})
const valueHtml = ref()
const visible = ref(false)

let ids = []

onMounted(() => {
  getList()
})

const ebookId = computed(() => {
  return route.query.ebookId
})

const handlePreview = () => {
  visible.value = true
}

const getDocName = (id) => {
  for (let doc of docList.value) {
    if (doc.id === id) return doc.name
  }
  return '无'
}

const handleAdd = () => {
  handleRest()
  treeList.value = copy(sourceTreeList.value)
  treeList.value.unshift({ id: 0, name: '无' })
}

const handleEdit = (row) => {
  form.value = JSON.parse(JSON.stringify(row))
  valueHtml.value = row.content
  treeList.value = copy(sourceTreeList.value)
  setDisable(treeList.value, row.id)
  treeList.value.unshift({ id: 0, name: '无' })
  queryContent(row.id)
}

const queryContent = async (id) => {
  const { success, data, message } = await getContent(id)
  if (success) {
    valueHtml.value = data
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}

const setDisable = (treeList, currentId) => {
  for (let item of treeList) {
    // 遍历到 父级节点
    if (item.id === currentId) {
      // 该节点禁用，同时该节点下的所有节点都得禁用
      item.disabled = true
      if (isNotEmpty(item.children)) {
        for (let child of item.children) {
          setDisable(item.children, child.id)
        }
      }
    } else {
      // 没有匹配到该节点，再去遍历其子节点
      if (isNotEmpty(item.children)) {
        setDisable(item.children, currentId)
      }
    }
  }
}

const getDeleteIds = (treeList, currentId) => {
  for (let item of treeList) {
    // 遍历到 父级节点
    if (item.id === currentId) {
      ids.push(item.id)
      if (isNotEmpty(item.children)) {
        for (let child of item.children) {
          getDeleteIds(item.children, child.id)
        }
      }
    } else {
      // 没有匹配到该节点，再去遍历其子节点
      if (isNotEmpty(item.children)) {
        getDeleteIds(item.children, currentId)
      }
    }
  }
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该数据？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 获取id之前先清空
      ids = []
      getDeleteIds(sourceTreeList.value, id)
      const { success, message } = await deleteDoc(ids)
      if (success) {
        handleRest()
        getList()
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      } else {
        ElMessage({
          type: 'error',
          message
        })
      }
    })
    .catch(() => {})
}

const handleRest = () => {
  form.value = {}
  valueHtml.value = ''
}

const handleSave = async () => {
  const { success, message } = await saveDoc({
    ...form.value,
    ebookId: ebookId.value,
    content: valueHtml.value
  })
  if (success) {
    handleRest()
    getList()
    ElMessage({
      type: 'success',
      message: '保存成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}

const getList = async () => {
  const { success, data, message } = await getDocAll(ebookId.value)

  if (success) {
    docList.value = copy(data)
    sourceTreeList.value = array2Tree(copy(data), 0)
    tableList.value = copy(sourceTreeList.value)
    treeList.value = copy(sourceTreeList.value)
    treeList.value.unshift({ id: 0, name: '无' })
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}

const handleQuery = () => {
  getList()
}
</script>

<style lang="scss" scoped></style>
